package com.zmn.oms.admin.controller.order;

import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.file.FileUtil;
import com.zmn.common.utils.office.ExcelUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.consts.GlobalConsts;
import com.zmn.mcc.cas.model.LoginStaff;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.mos.dubbo.interfaces.order.FactoryOrderRemoteService;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderDutyConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.exception.OmsBusinessException;
import com.zmn.oms.model.dto.order.zmn.FactoryBatchNewOrderDIO;
import com.zmn.oms.model.dto.order.zmn.FactoryNewOrderDTO;
import com.zmn.oms.zmn.normal.business.interfaces.order.FactoryOrderBatchBService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.io.File;
import java.util.List;

/**
 * 类描述：厂商单
 *
 * @author liuying
 * @date 2018/11/21 15:36
 */
@Controller
@RequestMapping("/order/factory")
public class OrderFactoryController extends OmsBaseController {
    private Logger logger = LoggerFactory.getLogger(OrderFactoryController.class);

    @Autowired
    private FactoryOrderBatchBService factoryOrderBatchBService;
    @Reference(version = com.zmn.mos.dubbo.utils.DubboConsts.INTERFACE_VERSION, timeout = 10000, check = false)
    private FactoryOrderRemoteService factoryOrderRemoteService;
//    @org.apache.dubbo.config.annotation.Reference(version = com.zmn.mer.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
//    private FactoryListRemoteService factoryListRemoteService;

    /**
     * 新增厂商订单z
     *
     * @return
     */
    @RequestMapping(value = "add")
    public ModelAndView add() {
        return createNormalOrderModelAndView("order/factoryAdd");
    }

    /**
     * 批量新增厂商订单
     *
     * @return
     */
    @RequestMapping(value = "batchAdd")
    public ModelAndView batchAdd() {
        return createNormalOrderModelAndView("order/factoryBatchAdd");
    }

    /**
     * 新增普通单
     *
     * @return
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("all")
    public ResultDTO saveOrder(@RequestBody @Valid FactoryNewOrderDTO order) {
        //try {
            logger.debug("新增厂商单：{}", order);
            logger.info("订单开始录入：{}", DateUtil.getNowTimestampMillis());

            order.setInputType(OrderConsts.ORDER_INPUT_TYPE_MANUAL);

            // 录入订单
            order.setReceiveEntranceId(GateTypeConsts.GATE_PLAT_BACKSTAGE);
            order.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);

            return ResultDTO.fail("厂商服务已下线");
            /*ResponseDTO<FactoryDRO> droResponseDTO = factoryListRemoteService.getFactoryById(order.getOrderFactory().getFactoryId());
            if (!droResponseDTO.isSuccess() || Objects.isNull(droResponseDTO.getData())){
                return ResultDTO.fail("查询厂商信息失败");
            }
            // 基础信息
            FactoryOrderAddDIO factoryOrderAddDIO = BeanMapper.map(order, FactoryOrderAddDIO.class);
            factoryOrderAddDIO.setOperatorIP(order.getIp());
            factoryOrderAddDIO.setFactoryId(order.getOrderFactory().getFactoryId());
            OrderBaseInfo orderBaseInfo = BeanMapper.map(order, OrderBaseInfo.class);
            orderBaseInfo.setChannelId(droResponseDTO.getData().getChannelId());
            factoryOrderAddDIO.setOrderBaseInfo(orderBaseInfo);
            // 用户信息
            UserDIO userDIO = BeanMapper.map(order, UserDIO.class);
            userDIO.setContactName(order.getUserName());
            factoryOrderAddDIO.setUserDIO(userDIO);
            // 产品信息
            OrderProductDIO orderProductDIO = new OrderProductDIO();
            OrderFactoryDTO orderFactoryDTO = order.getOrderFactory();
            orderProductDIO.setNumber(orderFactoryDTO.getFcProductNumber());
            orderProductDIO.setDutyTime(order.getDutyTime());
            orderProductDIO.setProductId(orderFactoryDTO.getProductId());
            orderProductDIO.setTariffId(orderFactoryDTO.getTariffId());
            orderProductDIO.setFaultIdList(orderFactoryDTO.getFaultIdList());
            orderProductDIO.setRemark(orderFactoryDTO.getRemark());
            factoryOrderAddDIO.setOrderProductList(Lists.newArrayList(orderProductDIO));
            factoryOrderAddDIO.setFactoryId(orderFactoryDTO.getFactoryId());
            // 快递信息
            List<OrderPostDIO> orderPostList = BeanMapper.mapList(order.getOrderPostList(), OrderPostDIO.class);
            factoryOrderAddDIO.setOrderPostList(orderPostList);
            // 厂商配件信息
            List<FactoryNewOrderPartDIO> orderPartPostList = BeanMapper.mapList(order.getOrderPartPostList(), FactoryNewOrderPartDIO.class);
            factoryOrderAddDIO.setOrderPartPostList(orderPartPostList);
            logger.info("厂商单#factoryOrderRemoteService#addOrder入参：[{}]", JSON.toJSONString(factoryOrderAddDIO));
            ResponseDTO<OrderAddDRO> responseDTO = factoryOrderRemoteService.addOrder(factoryOrderAddDIO);
            logger.info("厂商单#factoryOrderRemoteService#addOrder出参：[{}]", JSON.toJSONString(responseDTO));
            if (!responseDTO.isSuccess()){
                return ResultDTO.fail(responseDTO.getMessage());
            }

            OrderAddDRO orderAddDRO = responseDTO.getData();
            OrderBO orderBO = new OrderBO();
            OrderWork orderWork = new OrderWork();
            orderWork.setOrderId(orderAddDRO.getOrderId());
            orderWork.setWorkId(orderAddDRO.getOrderId());
            orderBO.setOrderWork(orderWork);
            return ResultDTO.success(orderBO);*/

            /*OrderBO orderBO = factoryOrderBService.insertOrder(order);

            logger.info("订单结束录入：{}", DateUtil.getNowTimestampMillis());
            logger.debug("新增普通单结果：{}", orderBO);

            // 新增订单日志
            this.addFcOrderEventLog(orderBO);

            // 工单自动流转
            OrderWork orderWork = orderBO.getOrderWork();
            workFlowContextBService.asyncAutoFlow(orderWork.getOrderId(), orderWork.getWorkId());
            return ResultDTO.success(orderBO);
        } catch (OmsBaseException ex) {
            return ResultDTO.fail(ex.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultDTO.fail(e.getMessage());
        }*/
    }

    /**
     * 批量新增工单
     *
     * @return
     */
    @RequestMapping(value = "batchSave", method = RequestMethod.POST)
    @ResponseBody
    @SuppressWarnings("all")
    public ResultDTO batchSaveOrder(@RequestBody @Valid List<FactoryBatchNewOrderDIO> orders) throws OmsBaseException {
        LoginStaff currStaff = StaffAdminService.currentStaff();
        try {
            factoryOrderBatchBService.batchInsertOrder(orders, (long) currStaff.getStaffId(), currStaff.getRealName(), currStaff.getType());
            return ResultDTO.success();
        } catch (OmsBaseException ex) {
            return ResultDTO.fail(ex.getMessage());
        } catch (OmsBusinessException ex) {
            return ResultDTO.fail(ex.getMessage());
        } catch (Exception ex) {
            return ResultDTO.fail(ex.getMessage());
        }
    }

    /**
     * 批量结算文件上传
     */
    @ResponseBody
    @RequestMapping(value = "/upload")
    public ResultDTO ajaxUpload(@RequestParam("file") MultipartFile file, @RequestParam(value="factoryId",required = false) Integer factoryId, @RequestParam(value="batchId",required = false) String batchId) throws InterruptedException {
        if (factoryId == null) {
            return ResultDTO.fail("请选择厂商");
        }

        if (file==null || file.getSize()<=0){
            return ResultDTO.fail("请上传文件!");
        }

        if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
            return ResultDTO.fail("请上传excel文件");
        }
        File toFile = null;

        LoginStaff currStaff = StaffAdminService.currentStaff();

        try {

            toFile = new File(file.getOriginalFilename());
            FileUtil.inputStreamToFile(file.getInputStream(),toFile);
            Workbook workbook = ExcelUtil.getWorkbook(toFile);
            Sheet sheet = workbook.getSheetAt(0);

            factoryOrderBatchBService.batchInsertOrder(sheet, factoryId, (long)currStaff.getStaffId(), currStaff.getRealName(), currStaff.getType(), batchId);

            return ResultDTO.success();
        } catch (OmsBaseException oe) {
            return ResultDTO.fail(oe.getMessage());
        } catch (Exception e) {
            logger.info(e.getMessage(),e);
            return ResultDTO.fail("文件上传失败!");
        } finally {

            //删除临时文件
            if(toFile != null){
                File del = new File(toFile.toURI());
                del.delete();
            }
        }
    }


    /**
     * 批量结算文件上传
     */
    @ResponseBody
    @RequestMapping(value = "/upload/progress")
    public ResultDTO ajaxUpload(@RequestParam(value="batchId",required = false) String batchId) {
        return ResultDTO.success(factoryOrderBatchBService.getImportingProgress(batchId));
    }

    /**
     * 创建普通工单的视图
     *
     * @param viewName 视图名称
     * @return
     */
    private ModelAndView createNormalOrderModelAndView(String viewName) {
        ModelAndView mav = new ModelAndView(viewName);
        // 平台
        mav.addObject("plat", GlobalConsts.PLAT_MARK_YEYX);
        // 业务类型
        mav.addObject("bizTypeList", super.dictModel2KVDict(OrderConsts.getOrderBizTypeFAndCList()));
        // 性别
        mav.addObject("gender", super.dictModel2KVDict(GlobalDict.getGenderList()));
        // 订单类型
        mav.addObject("type", super.dictModel2KVDict(OrderConsts.getOrderTypeList()));
        // 厂商列表
        mav.addObject("factoryList", super.getFactoryListByDept(true));
        // 省份
        mav.addObject("provinceList", super.getProvinceListByDept());
        // 城市ID
        mav.addObject("cityList", super.getAllCityList());
        // 预约失败原因
        mav.addObject("dutyFailReasonList", super.dictModel2KVDict(OrderDutyConsts.getDutyFailReasonList()));

        mav.addObject("productShowType", super.dictModel2KVDict(OrderConsts.getProductShowTypeList()));
        // 服务分类
        mav.addObject("servCategList", super.getShowServCategList());
        //物流公司
        mav.addObject("expressCompanyList", super.listExpressCompany());

        return mav;
    }

    /**
     * 新增订单埋点
     *
     * @param orderBO
     */
    /*private void addFcOrderEventLog(OrderBO orderBO) {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            HttpServletRequest httpServletRequest = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
            String userAgentStr = httpServletRequest.getHeader("User-Agent");
            UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
            final String site = "zmn-oms-admin";

            OrderWork orderWork = orderBO.getOrderWork();

            OrderDetail orderDetail = orderBO.getOrderDetail();
            List<OrderProduct> orderProductList = orderBO.getOrderProductList();
            OrderProduct orderProduct = orderProductList.get(0);

            AddOrderEventLogItem eventLogItem = new AddOrderEventLogItem();
            eventLogItem.setBizId(String.valueOf(orderWork.getOrderId()));
            eventLogItem.setOrderId(String.valueOf(orderWork.getOrderId()));
            if (NumberUtil.isNotNullOrZero(orderProduct.getProductId())) {
                eventLogItem.setProductId(String.valueOf(orderProduct.getProductId()));
                eventLogItem.setProductName(orderProduct.getProductName());
            } else {
                eventLogItem.setProductId(String.valueOf(orderProduct.getShowProductId()));
                eventLogItem.setProductName(orderProduct.getShowProductName());
            }
            eventLogItem.setChannelId(String.valueOf(orderWork.getChannelId()));
            eventLogItem.setOrderChannelId(String.valueOf(orderWork.getChannelId()));
            eventLogItem.setSourceChannelId(String.valueOf(orderWork.getSourceChannelId()));
            eventLogItem.setLng(Objects.isNull(orderDetail.getLongitude()) ? "" : String.valueOf(orderDetail.getLongitude()));
            eventLogItem.setLat(Objects.isNull(orderDetail.getLatitude()) ? "" : String.valueOf(orderDetail.getLatitude()));
            eventLogItem.setSite(site);

            UserLogItem staffUserLogItem = new UserLogItem();
            staffUserLogItem.setUserType(UserType.STAFFER);
            staffUserLogItem.setUserId(String.valueOf(super.getCurrentStaff().getStaffId()));
            staffUserLogItem.setUserName(super.getCurrentStaff().getStaffName());

            DeviceLogItem deviceLogItem = new DeviceLogItem();
            deviceLogItem.setIp(HttpUtil.getIPAddress(httpServletRequest));
            if (Objects.nonNull(userAgent)) {
                deviceLogItem.setBrowser(userAgent.getBrowser().getName());
                deviceLogItem.setOs(userAgent.getOperatingSystem().getName());
            }

            EntryLogItem entryLogItem = new EntryLogItem();
            entryLogItem.setEntryType(String.valueOf(GateTypeConsts.GATE_TYPE_PLAT));
            entryLogItem.setEntry(String.valueOf(GateTypeConsts.GATE_PLAT_BACKSTAGE));

            AddUserOperationLogRequest<AddOrderEventLogItem> request = new AddUserOperationLogRequest<>();
            request.setUser(staffUserLogItem);
            request.setEntry(entryLogItem);
            request.setDevice(deviceLogItem);
            request.setEvent(eventLogItem);
            request.setClientName(site);

            logClient.addAddOrderEventLog(request);
        } catch (Exception e) {
            logger.error("addLookOrderEventLog error：", e);
        }
    }*/
}
